const parser = require('@babel/parser')
const traverse = require('@babel/traverse').default
const createHtmlDom = require('htmldom')
const fs = require('fs')
function print(color, msg) {
  let map = {
    bright: '\x1B[1m', // 亮色
    grey: '\x1B[2m', // 灰色
    italic: '\x1B[3m', // 斜体
    underline: '\x1B[4m', // 下划线
    reverse: '\x1B[7m', // 反向
    hidden: '\x1B[8m', // 隐藏
    black: '\x1B[30m', // 黑色
    red: '\x1B[31m', // 红色
    green: '\x1B[32m', // 绿色
    yellow: '\x1B[33m', // 黄色
    blue: '\x1B[34m', // 蓝色
    magenta: '\x1B[35m', // 品红
    cyan: '\x1B[36m', // 青色
    white: '\x1B[37m', // 白色
    blackBG: '\x1B[40m', // 背景色为黑色
    redBG: '\x1B[41m', // 背景色为红色
    greenBG: '\x1B[42m', // 背景色为绿色
    yellowBG: '\x1B[43m', // 背景色为黄色
    blueBG: '\x1B[44m', // 背景色为蓝色
    magentaBG: '\x1B[45m', // 背景色为品红
    cyanBG: '\x1B[46m', // 背景色为青色
    whiteBG: '\x1B[47m' // 背景色为白色
  }
  console.log(map[color] || map['bright'], msg, '\x1b[0m')
}
// 校验白名单，白名单内的vue文件不参与校验
let whiteList = [
  'src/components/dragVerify.vue',
  'src/pages/exam/cpa_exam/components/coefficientTableDialog.vue',
  'src/pages/exam/mock_exam_index/components/dialog.vue',
  'src/pages/exam/mock_exam_new/components/dialog.vue',
  'src/pages/exam/single_question/components/compose_question.vue',
  'src/pages/exam/sprint_activity/components/right_box_com.vue',
  'src/pages/fileapp/policy.vue',
  'src/pages/fileapp/protocol.vue',
  'src/pages/exam/mock_exam_do/index.vue'
]
// excuteVuePath：被校验的vue文件路径
let excuteVuePath = process.argv[2]
excuteVuePath = excuteVuePath.trim()
// 白名单内文件不参与校验
if (whiteList.includes(excuteVuePath)) {
  print('green', `[${excuteVuePath}]:vueLint passed`)
  process.exit(0)
}
let fileContent = fs.readFileSync(excuteVuePath).toString()
let $ = createHtmlDom(fileContent)
let scriptsAll = $('script')

let currentScripts = ''
scriptsAll.each(function(index,item) {
  if (currentScripts) return
  if (!item.attributes.src) {
    currentScripts = item
  }
})
if (!currentScripts) {
  process.exit(0)
}
jsCode = $(currentScripts).html()
if (!jsCode) process.exit(0)
// 解析js代码为AST
let configJsTree = parser.parse(jsCode, {
  sourceType: 'module'
})
// 遍历AST
traverse(configJsTree, {
  enter(path) {
    if (path.node.type === 'ExportDefaultDeclaration' && path.node.declaration.type === 'ObjectExpression') {
      // 非白名单中的vue文件中不能包含created，下面这两种形式均会被检测出来，若包含“created”方法，则通不过校验。
      /*
        {
          created() {},
          created: function() {}
        }
      */
      let isExistCreated = path.node.declaration.properties.find(item => item.key.name === 'created')
      if (isExistCreated) {
        print('red', `[${excuteVuePath}]:vueLint failed, your code includes "created", please remove it`)
        process.exit(1)
      }
    }
  }
})
print('green', `[${excuteVuePath}]:vueLint passed`)
process.exit(0)
